import tkinter as tk
from tkinter import *
from tkinter import simpledialog, messagebox
import matplotlib.pyplot as plt
import numpy as np


def plot_bar_chart(data, labels):
    plt.bar(labels, data)
    plt.xlabel('类别')
    plt.ylabel('数值')
    plt.title('柱状图')
    plt.show()


def plot_pie_chart(data, labels):
    plt.pie(data, labels=labels, autopct='%1.1f%%', startangle=140)
    plt.title('饼图')
    plt.show()


def plot_regression_curve(x, y):
    coefficients = np.polyfit(x, y, deg=1)
    polynomial = np.poly1d(coefficients)
    plt.scatter(x, y, color='blue')
    plt.plot(x, polynomial(x), color='red')
    plt.xlabel('X 轴')
    plt.ylabel('Y 轴')
    plt.title('回归曲线')
    plt.show()


def is_valid_triangle(a, b, c):
    return a + b > c and a + c > b and b + c > a


def plot_triangle(a, b, c):
    if not is_valid_triangle(a, b, c):
        messagebox.showerror("错误", "无法绘制该三角形")
        return
    A = np.array([0, 0])
    C = np.array([c, 0])
    B_x = (a**2 + c**2 - b**2) / (2 * c)
    B_y = np.sqrt(a**2 - B_x**2)
    B = np.array([B_x, B_y])
    plt.figure()
    plt.plot([A[0], B[0], C[0], A[0]], [A[1], B[1], C[1], A[1]], 'bo-')
    plt.fill([A[0], B[0], C[0]], [A[1], B[1], C[1]], 'b', alpha=0.3)
    plt.title('三角形绘制')
    plt.xlabel('X 轴')
    plt.ylabel('Y 轴')
    plt.grid(True)
    plt.axis('equal')
    plt.show()


def plot_handler(parent_window):
    def handle_selection():
        plot_type = plot_var.get()
        if plot_type == "柱状图":
            labels = simpledialog.askstring("输入", "请输入标签（用逗号分隔）:").split(',')
            data = list(map(float, simpledialog.askstring("输入", "请输入数据（用逗号分隔）:").split(',')))
            plot_bar_chart(data, labels)
        elif plot_type == "饼图":
            data = list(map(float, simpledialog.askstring("输入", "请输入数据（用逗号分隔）:").split(',')))
            labels = [f"部分 {i + 1}" for i in range(len(data))]
            plot_pie_chart(data, labels)
        elif plot_type == "回归曲线":
            x = list(map(float, simpledialog.askstring("输入", "请输入 X 值（用逗号分隔）:").split(',')))
            y = list(map(float, simpledialog.askstring("输入", "请输入 Y 值（用逗号分隔）:").split(',')))
            plot_regression_curve(x, y)
        elif plot_type == "三角形":
            a = float(simpledialog.askstring("输入", "请输入边长 a（最长边）:"))
            b = float(simpledialog.askstring("输入", "请输入边长 b:"))
            c = float(simpledialog.askstring("输入", "请输入边长 c:"))
            plot_triangle(a, b, c)

    plot_window = Toplevel(parent_window)
    plot_window.title("选择绘图类型")
    plot_window.geometry("300x200")

    plot_var = StringVar(value="柱状图")
    options = ["柱状图", "饼图", "回归曲线", "三角形"]
    Label(plot_window, text="请选择绘图类型:", font=("Arial", 12)).pack(pady=10)
    for option in options:
        Radiobutton(plot_window, text=option, variable=plot_var, value=option).pack(anchor=W)

    Button(plot_window, text="确定", command=handle_selection).pack(pady=10)
    Button(plot_window, text="关闭", command=plot_window.destroy).pack(pady=10)
